using System.Reflection;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using ApiDoc.Shared;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
//配置Swagger
builder.Services.AddSwaggerGen(options =>
{
	options.SwaggerDoc("v1", new OpenApiInfo
	{
		Version = "v1",
		Title = "This is my Knife4j UI API"
	});
	var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
	var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
	options.IncludeXmlComments(xmlPath, true);
	options.OrderActionsBy(o => o.RelativePath);
});

//配置JWT
builder.Services
	.AddAuthorization()
	.AddAuthentication(x =>
	{
		x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
		x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
	})
	.AddJwtBearer(x =>
	{
		x.RequireHttpsMetadata = false;
		x.SaveToken = true;
		x.TokenValidationParameters = new TokenValidationParameters
		{
			ValidateIssuerSigningKey = false,
			IssuerSigningKey = new SymmetricSecurityKey("<your_jwt_key>"u8.ToArray()),
			ValidateIssuer = false,
			ValidateAudience = false
		};
	});

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
	app.UseSwagger();
	app.UseKnife4UI(c =>
	{
		c.RoutePrefix = string.Empty;
		c.SwaggerEndpoint("/swagger/v1/swagger.json","v1");
	});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
#region Endpoints
var summaries = new[]
{
	"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
var group1 = app.MapGroup("/api")
	.WithTags("weatherforecast");
group1.MapGet("/weatherforecast", () =>
	{
		var forecast = Enumerable.Range(1, 5).Select(index =>
				new WeatherForecast
				(
					DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
					Random.Shared.Next(-20, 55),
					summaries[Random.Shared.Next(summaries.Length)]
				))
			.ToArray();
		return forecast;
	})
	.WithName("GetWeatherForecast");
var group2 = app.MapGroup("/api")
	.WithTags("test");
group2.MapGet("/test1", () => "This is test 1 endpoint")
	.WithName("Test1")
	.RequireAuthorization();
group2.MapGet("/test2", () => "This is test 2 endpoint")
	.WithName("Test2");
#endregion
app.Run();
